package com.easemob.helpdesk.activity.chat;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.widget.VideoView;

import com.easemob.helpdesk.activity.ContextMenu;
import com.easemob.helpdesk.utils.CommonUtils;
import com.easemob.helpdesk.utils.DownloadManager;
import com.housekeeperapp.R;
import com.easemob.helpdesk.activity.BaseActivityV2;
import com.hyphenate.kefusdk.HDDataCallBack;
import com.hyphenate.kefusdk.chat.HDClient;
import com.hyphenate.kefusdk.entity.HDMessage;
import com.hyphenate.kefusdk.utils.HDLog;
import com.hyphenate.util.PathUtil;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * 展示视频内容
 *
 */
public class ShowVideoActivity extends BaseActivityV2 {
	private static final String TAG = "ShowVideoActivity";

	private RelativeLayout loadingLayout;
	private ProgressBar progressBar;
	private String localFilePath;
	private VideoView videoView;
	private RelativeLayout video_view_layout;

	private HDMessage message;

	public static final int REQUEST_CODE_CONTEXT_MENU = 0x011;
//	public static final int RES_CODE_SAVE = 0x022;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.hd_showvideo_activity);
		loadingLayout = (RelativeLayout) findViewById(R.id.loading_layout);
		progressBar = (ProgressBar) findViewById(R.id.progressBar);

		videoView = (VideoView)this.findViewById(R.id.video_view);
		video_view_layout = (RelativeLayout) this.findViewById(R.id.video_view_layout);

		localFilePath = getIntent().getStringExtra("localpath");
		String remotepath = getIntent().getStringExtra("remotepath");
		String secret = getIntent().getStringExtra("secret");
		message = getIntent().getParcelableExtra("videomsg");
		HDLog.d(TAG, "show video view file:" + localFilePath
				+ " remotepath:" + remotepath + " secret:" + secret);

		if (localFilePath != null && new File(localFilePath).exists()) {

//			Intent intent = new Intent(Intent.ACTION_VIEW);
//			intent.setDataAndType(Uri.fromFile(new File(localFilePath)),
//					"video/mp4");
//			startActivity(intent);
//			finish();

			loadingLayout.setVisibility(View.GONE);
			showLocalVideo(localFilePath);

		} else if (!TextUtils.isEmpty(remotepath) && !remotepath.equals("null")) {
			HDLog.d(TAG, "download remote video file");
			Map<String, String> maps = new HashMap<String, String>();
			if (!TextUtils.isEmpty(secret)) {
				maps.put("share-secret", secret);
			}
			downloadVideo(remotepath, message , maps);
		} else {

		}

		videoView.setZOrderOnTop(true);
		video_view_layout.setOnLongClickListener(new View.OnLongClickListener() {
			@Override
			public boolean onLongClick(View view) {
				Intent intent = new Intent(ShowVideoActivity.this, ContextMenu.class);
				intent.putExtra("type", ContextMenu.TYPE_CONTEXT_MENU_VIDEO);

				startActivityForResult(intent, REQUEST_CODE_CONTEXT_MENU);
				return true;
			}
		});


	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == REQUEST_CODE_CONTEXT_MENU) {
			if (resultCode == MsgShowVideoActivity.RES_CODE_SAVE) {
				File file = new File(localFilePath);
				String down_path = DownloadManager.getSDPATH() + file.getName();

				CommonUtils.copyFile(localFilePath, down_path);

				Toast.makeText(this, "已成功保存到"+DownloadManager.getSDPATH(), Toast.LENGTH_LONG).show();
			}
		}

	}

	public String getLocalFilePath(String remoteUrl) {
		String localPath;
		if (remoteUrl.contains("/")) {
			localPath = PathUtil.getInstance().getVideoPath().getAbsolutePath()
					+ "/" + remoteUrl.substring(remoteUrl.lastIndexOf("/") + 1)
					+ ".mp4";
		} else {
			localPath = PathUtil.getInstance().getVideoPath().getAbsolutePath()
					+ "/" + remoteUrl + ".mp4";
		}
		return localPath;
	}

	/**
	 * 播放本地视频
	 *
	 * @param localPath 视频路径
	 */
	private void showLocalVideo(String localPath) {
//		Intent intent = new Intent(Intent.ACTION_VIEW);
//		intent.setDataAndType(Uri.fromFile(new File(localPath)),
//				"video/mp4");
//		startActivity(intent);
//		finish();

		video_view_layout.setVisibility(View.VISIBLE);

		videoView.setMediaController(new MediaController(this));
		videoView.setVideoURI(Uri.fromFile(new File(localPath)));
		videoView.requestFocus();
		videoView.start();

	}


	/**
	 * 下载视频文件
	 */
	private void downloadVideo(final String remoteUrl, HDMessage message,
	                           final Map<String, String> header) {

		if (TextUtils.isEmpty(localFilePath)) {
			localFilePath = getLocalFilePath(remoteUrl);
		}
		if (new File(localFilePath).exists()) {
			showLocalVideo(localFilePath);
			return;
		}
		loadingLayout.setVisibility(View.VISIBLE);

		message.setMessageCallback(new HDDataCallBack() {
			@Override
			public void onSuccess(Object o) {
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						loadingLayout.setVisibility(View.GONE);
						progressBar.setProgress(0);
						showLocalVideo(localFilePath);
					}
				});
			}

			@Override
			public void onProgress(final int progress) {
				HDLog.d("ease", "video progress:" + progress);
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						progressBar.setProgress(progress);
					}
				});

			}

			@Override
			public void onError(int error, String msg) {
				HDLog.e("###", "offline file transfer error:" + msg);
				File file = new File(localFilePath);
				if (file.exists()) {
					file.delete();
				}
			}
		});
		HDClient.getInstance().chatManager().downloadAttachment(message);
	}

	@Override
	public void onBackPressed() {
		finish();
	}


}
